from cron_converter import Cron
import time, datetime, functools
import os, feedparser
from urllib.request import ProxyHandler
from common import Config, DbHelper

class QingtingfmCrawler(Config):
    def __init__(self):
        self.db = DbHelper()

    def crawl(self):
        playbill = self.load_config('qingtingfm.json5')
        now = datetime.datetime.now()
        ymd = now.strftime("%Y%m%d")
        md = ymd[4:6]+'-'+ymd[6:]

        for (name, channel, period) in playbill:
            pd = period[0:4]+'_'+period[7:11]
            dt = now.replace(hour=int(period[7:9])).replace(minute=int(period[9:11]))
            diff = (now - dt).total_seconds()
            if diff<0 or diff >30*60:  # 播完后不超过半小时
                continue
            title = f'{name} {md} {pd}'
            link = f"https://www.qingting.fm/radios/{channel}/?{ymd}_{period}"
            audio_url = f"https://lcache.qtfm.cn/cache/{ymd}/{channel}/{channel}_{ymd}_{period}_24_0.aac"
            if self.db.is_existed_rss_item(link):
                continue
            try:
                self.db.insert_rss_item(title, link, audio_url)
            except Exception as e:
                print("ERROR: insert rss item: "+str(e))
        
        self.db.close()